<template>
    <el-card>
        <div class="w-1/3 flex h-8" style="">
            <el-input type="text" clearable v-model="queryData.content" style="border-color: rgb(231, 179, 82)"
                placeholder="请输入内容进行检索">
                <template #prepend>
                    <el-button icon="Search" />
                </template>
                <template #append>
                    <el-select v-model="queryData.flag" placeholder="Select" style="width: 115px">
                        <el-option label="药品序号" value="4" />
                        <el-option label="企业名称" value="5" />
                        <el-option label="药品名称" value="1" />
                    </el-select>
                </template>
            </el-input>
            <el-button class="bg-blue-400" :loading="loading" style="height: 100%" type="primary"
                @click="initData">确定</el-button>
        </div>
        <div class="mt-4">
            <el-button class=" bg-blue-500" type="primary" @click="handleExpand">折叠全部</el-button>
            <el-button class=" bg-blue-500" type="primary" @click="handleOpen">展开全部</el-button>
            <el-button class=" bg-blue-500" type="primary" @click="dialogVisible = true">新增药品</el-button>
        </div>
    </el-card>

    <el-card class="mt10">
        <el-table ref="table" :data="tableData" :header-cell-style="{ backgroundColor: '#ecf5ff' }" border stripe
            style="width: 100%">
            <el-table-column type="expand">
                <template #default="props">
                    <div class="m10">
                        <div class="expand-title">药品信息</div>
                        <el-table :header-cell-style="{ backgroundColor: '#FAFAFA' }" :data="props.row.infoDetailList"
                            border style="border-bottom: none">
                            <el-table-column v-for="ctx in ItemData" :key="ctx.props" :sortable="ctx.sortable"
                                :prop="ctx.props" :label="ctx.label" :width="ctx.width" :fixed="ctx.fixed"
                                :align="ctx.align" show-overflow-tooltip>
                            </el-table-column>
                        </el-table>
                    </div>
                </template>
            </el-table-column>
            <el-table-column v-for="item in columnData" :key="item.props" :sortable="item.sortable" :prop="item.props"
                :label="item.label" :width="item.width" :fixed="item.fixed" :align="item.align" show-overflow-tooltip>
                <template v-slot:default="scope" v-if="item.props !== 'actions'">
                    <el-input v-model="scope.row[item.props]" v-if="scope.row.itemEdit"></el-input>
                    <div v-else class="one-cut-txt">{{ scope.row[item.props] }}</div>
                </template>
                <template v-slot:default="scope" v-if="item.props === 'actions'">
                    <el-icon class="icon-edit" @click="itemEditHanld(scope.row)">
                        <Finished v-if="scope.row.itemEdit" />
                        <Edit v-else />
                    </el-icon>
                    <el-popconfirm confirm-button-text="确认" cancel-button-text="取消" :icon="InfoFilled" icon-color="#626AEF"
                        title="确认删除该数据?" @confirm="DeleteItem(scope.row)">
                        <template #reference>
                            <el-icon class="icon-dele">
                                <Delete />
                            </el-icon>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination class=" ml-48 mt-4" background v-model:current-page="queryData.currentPage"
            v-model:page-size="queryData.pageSize" :page-sizes="[10, 20, 30, 40]" small="small"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
    </el-card>

    <el-dialog v-model="dialogVisible" title="添加药品" width="50%" :before-close="handleClose" draggable>
        <el-form :model="druginfo" label-width="120px">
            <el-form-item label="药品名称">
                <el-input v-model="druginfo.name" />
            </el-form-item>
            <el-form-item label="批准文号">
                <el-input v-model="druginfo.approvalNo" />
            </el-form-item>
            <el-form-item label="生产企业">
                <el-input v-model="druginfo.pc" />
            </el-form-item>
            <el-form-item label="相关标签">
                <el-select v-model="druginfo.label" multiple filterable allow-create default-first-option
                    :reserve-keyword="false" placeholder="添加相关标签">
                    <el-option v-for="item in selectOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="药品成分">
                <el-input v-model="druginfo.composition" maxlength="80" placeholder="请输入药品的药品成分" show-word-limit
                    type="textarea" />
            </el-form-item>
            <el-form-item label="适应症状">
                <el-input v-model="druginfo.indication" maxlength="80" placeholder="请输入适应症状" show-word-limit
                    type="textarea" />
            </el-form-item>
            <el-form-item label="用法用量">
                <el-input v-model="druginfo.illustrate" maxlength="80" placeholder="请输入药品的用法用量" show-word-limit
                    type="textarea" />
            </el-form-item>
            <el-form-item label="功能主治">
                <el-input v-model="druginfo.drugFunction" maxlength="100" placeholder="请输入药品的功能主治" show-word-limit
                    type="textarea" />
            </el-form-item>
            <el-form-item label="药品库存">
                <el-input-number v-model="druginfo.num" :step="2" />
            </el-form-item>
            <el-form-item label="参考报价">
                <el-input-number v-model="druginfo.price" :precision="2" :step="1.20" :max="1000" />
            </el-form-item>
            <el-form-item label="药品图片">
                <el-upload :before-upload="beforeAvatarUpload" :headers="headers" :on-success="handleAvatarSuccess"
                    v-model:file-list="fileList" class="upload-demo" action="api/drug/upload" :on-preview="handlePreview"
                    :on-remove="handleRemove" list-type="picture">
                    <el-button type="primary" class=" bg-blue-500">Click to upload</el-button>
                    <template #tip>
                        <div class="el-upload__tip">
                            jpg/png files with a size less than 500kb
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleCancel">取消</el-button>
                <el-button class=" bg-blue-500" type="primary" @click="handleInsert">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup>
import {
    Edit,
    Delete,
    InfoFilled,
} from '@element-plus/icons-vue'
import { nextTick, onMounted, reactive, ref } from 'vue'
import { getDrugList, deleteDrug, insertDrug, updateDrug } from '../../api/modules/druginfo'
import { options, ItemData } from './options'
import { useStore } from "vuex";
import { useRouter } from 'vue-router';
import { ElNotification, ElMessageBox } from 'element-plus';
import { logout } from '../../api/modules';
const tableData = ref([])
const router = useRouter()
const store = useStore()
const table = ref()
const isExpand = ref(false)
const disabled = ref(false)
const dialogVisible = ref(false)
const total = ref(0)
const headers = { token: store.getters.token }
const loading = ref(false)
const columnData = ref(JSON.parse(JSON.stringify(options)))
const formInline = ref({})
const fileList = ref()
const queryData = ref({
    currentPage: 1,
    pageSize: 10,
    content: '',
    flag: ''
})
const handleClose = (done) => {
    ElMessageBox.confirm('您确定关闭对话框吗？')
        .then(() => {
            done()
            resetForm()
        })
        .catch(() => {
            // catch error
        })
}
const selectOptions = [
    {
        value: '感冒药',
        label: '感冒药',
    },
    {
        value: '肠胃药',
        label: '肠胃药',
    },
    {
        value: '皮肤药',
        label: '皮肤药',
    },
]
const druginfo = reactive({
    name: '',
    indication: '',
    composition: '',
    drugFunction: '',
    illustrate: '',
    approvalNo: '',
    pc: '',
    price: '',
    label: '',
    num: '',
    url: ''
})
const handleCancel = () => {
    resetForm()
    dialogVisible.value = false
}
const resetForm = () => {
    druginfo.approvalNo = ''
    druginfo.composition = ''
    druginfo.drugFunction = ''
    druginfo.illustrate = ''
    druginfo.label = ''
    druginfo.name = ''
    druginfo.num = ''
    druginfo.pc = ''
    druginfo.price = ''
    druginfo.url = ''
    druginfo.indication = ''
    fileList.value = []
}
const handleInsert = async () => {
    dialogVisible.value = true
    let data = ''
    let i = 1;
    druginfo.label.forEach((item) => {
        if (i < druginfo.label.length) {
            data = data + item + ','
        } else {
            data = data + item + ''
        }
        i++;
    })
    druginfo.label = data;
    let res = await insertDrug(druginfo)
    if (res.data.data > 0) {
        ElNotification.success("添加成功")
    } else {
        ElNotification.error("添加失败")
    }
    resetForm()
    dialogVisible.value = false
}
const initData = async () => {
    loading.value = true
    tableData.value = []
    let res = await getDrugList(queryData.value)
    total.value = res.data.data.total
    res.data.data.records.forEach((item) => {
        tableData.value.push(item)
    })
    loading.value = false
}
const DeleteItem = async (item) => {
    let res = await deleteDrug(item.id)
    if (res.data.data > 0) {
        ElNotification.success("删除成功")
        let res1 = await getDrugList(queryData.value)
        tableData.value = []
        res1.data.data.records.forEach((item) => {
            tableData.value.push(item)
        })
    } else {
        ElNotification.error("删除失败")
    }
}
const itemEditHanld = async (item) => {
    item.itemEdit = !item.itemEdit
    if (item.itemEdit == false) {
        let res = await updateDrug(item)
        if (res.data.data > 0) {
            ElNotification.success('更新成功')
        }
    }
}
const handleSizeChange = (val) => {
    queryData.value.pageSize = val
    initData(queryData.value)
}
const handleSelectionChange = (val) => {

}
const handleCurrentChange = (val) => {
    queryData.value.currentPage = val
    initData(queryData.value)
}
const dialogVisibleHanle = () => {
    console.log('滑动加载')
}
const handleExpand = () => {
    isExpand.value = false
    tableData.value.forEach((item) => {
        table.value.toggleRowExpansion(item, isExpand.value)
    })
}

const handleOpen = () => {
    isExpand.value = true
    tableData.value.forEach((item) => {
        table.value.toggleRowExpansion(item, isExpand.value)
    })
}
const handleRemove = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}

const handlePreview = (file) => {
    console.log(file)
}
const handleAvatarSuccess = async (response,
    uploadFile) => {
    if (response.code == 200) {
        druginfo.url = response.data
        ElNotification.success("图片上传成功")
    } else if (response.code == 401) {
        fileList.value = []
        router.push("/login")
        let res = await logout()
        if (res.data.code == 200) {
            localStorage.removeItem("token")
            localStorage.removeItem("user")
            localStorage.removeItem("menu")
            sessionStorage.removeItem("UserInfo")
            setTimeout(() => {
                alert("信息发生变化，请重新登录")
                router.push("/login")
            }, 1000)
        }
    } else {
        fileList.value = []
        ElNotification.error("图片上传失败，请重新上传")
    }
}
const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}
onMounted(() => {
    initData()
})
</script>
  
<style lang="scss" scoped>
.mt-4 {
    float: right;
    text-align: right;
    margin-bottom: 20px;
}

.demo-form-inline {}

.dragClass {
    background: rgba($color: #41c21a, $alpha: 0.5) !important;
}

// 停靠
.ghostClass {
    background: rgba($color: #6cacf5, $alpha: 0.5) !important;
}

// 选择
.chosenClass:hover>td {
    background: rgba($color: #f56c6c, $alpha: 0.5) !important;
}

.icon-view {
    font-size: 20px;
    color: #673ab7;
    margin: 0 10px;
}

.icon-edit {
    font-size: 20px;
    color: #2f60c2;
    margin: 0 10px;
}

.icon-dele {
    font-size: 20px;
    color: #ff5722;
}

.btn-color {
    background: #fff;
    color: #4c60cc;
}

.expand-title {
    padding: 10px;
    color: #919399;
    font-weight: 600;
}
</style>
  